package com.tanjun.web.config;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.tanjun.common.constants.HeaderConstant;
import com.tanjun.common.model.LoginUserInfo;
import com.tanjun.web.service.LoginUserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 请求之前，先将用户信息放入到ThreadLocal中
 * 清除ThreadLocal中数据
 * 1.防止内存泄漏
 * 2.防止线程复用的时候，后续请求会获取的上次数据
 */
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {
    /**
     * 请求处理之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String strUserInfo= URLDecoder.decode(request.getHeader(HeaderConstant.USER_INFO),StandardCharsets.UTF_8);
        String strUserRoles=request.getHeader(HeaderConstant.USER_ROLES);
        log.info("ThreadLocal设置用户信息，url:{},用户信息:{}",request.getRequestURI(),strUserInfo);
        LoginUserInfo loginUserInfo=null;
        if(!StrUtil.isEmpty(strUserInfo)){
            loginUserInfo= JSONObject.parseObject(strUserInfo,LoginUserInfo.class);
        }
        LoginUserContext.setLoginUserInfo(loginUserInfo);

        String strPermission=request.getHeader(HeaderConstant.USER_PERMISSION);

        if (StrUtil.isNotEmpty(strPermission)) {
            List<String> permissions=StrUtil.split(strPermission,",");
            LoginUserContext.setPermissionVersion(permissions);
        }
        if(StrUtil.isNotEmpty(strUserRoles)){
            List<String> roles=StrUtil.split(strUserRoles,",");
            LoginUserContext.setUserRoles(roles);
        }

        return true;
    }



    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView){
        log.info("ThreadLocal清除用户信息，url:{}",request.getRequestURI());
        LoginUserContext.clearUserInfo();
        LoginUserContext.clearPermission();
        LoginUserContext.clearUserRoles();
   }
}
